package com.cabinet.ui;

import com.cabinet.Config;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

/**
 * Created with IntelliJ IDEA.
 * User: lesya
 * Date: 12/9/13
 * Time: 9:19 AM
 * To change this template use File | Settings | File Templates.
 */
public class SelectionRectangle implements MouseListener, MouseMotionListener{
  JPanel panel = new JPanel();
  JLabel rect = new JLabel();
  XY from = null;

  static class XY{
    int x,y;

    XY(int x, int y) {
      this.x = x;
      this.y = y;
    }
  }

  public SelectionRectangle(JPanel panel) {
    this.panel = panel;
    rect.setBorder(BorderFactory.createLineBorder(Color.GREEN, 4));
    panel.add(rect);
    rect.setSize(0,0);
    rect.setLocation(200,200);
    panel.addMouseListener(this);
    panel.addMouseMotionListener(this);
  }

  @Override
  public void mouseClicked(MouseEvent mouseEvent) {
    //To change body of implemented methods use File | Settings | File Templates.
  }

  @Override
  public void mousePressed(MouseEvent e) {
    if( Config.left(e) ){
      rect.setSize(0,0);
      rect.setLocation(e.getX(), e.getY());
      from = new XY(e.getX(), e.getY());
    }
  }

  @Override
  public void mouseReleased(MouseEvent mouseEvent) {
    from = null;
    rect.setSize(0,0);
  }

  @Override
  public void mouseEntered(MouseEvent mouseEvent) {
    //To change body of implemented methods use File | Settings | File Templates.
  }

  @Override
  public void mouseExited(MouseEvent mouseEvent) {
    //To change body of implemented methods use File | Settings | File Templates.
  }

  @Override
  public void mouseDragged(MouseEvent e) {
    if( from != null ){
      int minX = Math.min(e.getX(), from.x);
      int minY = Math.min(e.getY(), from.y);
      int maxX = Math.max(e.getX(), from.x);
      int maxY = Math.max(e.getY(), from.y);

      rect.setBounds(minX, minY, maxX-minX, maxY-minY);
      selectIntersect();
    }
  }

  @Override
  public void mouseMoved(MouseEvent mouseEvent) {
    //To change body of implemented methods use File | Settings | File Templates.
  }

  void selectIntersect(){
    for( Component c : panel.getComponents() ){
      if( c instanceof DevicePanel ){
        DevicePanel devicePanel = (DevicePanel)c;
        if( rect.getBounds().intersects(devicePanel.getBounds()) ){
          if( ! devicePanel.groupSelected ){
            devicePanel.setGroupSelected(true);
          }
        }
      }
    }
  }
}
